package com.hang.ad.index.adunit;

import com.hang.ad.index.IndexAware;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class AdUnitIndex implements IndexAware<Long, AdUnitObject> {
    private static Map<Long, AdUnitObject> map;
    static {
        map = new ConcurrentHashMap<Long, AdUnitObject>();
    }
    public Set<Long> match(Integer positionType){
        Set<Long> adUnitIds = new HashSet<>();
        map.forEach((k,v) -> {
            if (AdUnitObject.isAdSlotTypeOK(positionType, v.getPositionType())){
                adUnitIds.add(k);
            }
        });
        return adUnitIds;
    }

    public List<AdUnitObject> fetch(Collection<Long> adUnitIds){
        if (CollectionUtils.isEmpty(adUnitIds)){
            return Collections.emptyList();
        }
        List<AdUnitObject> result = new ArrayList<>();

        adUnitIds.forEach(u -> {
            AdUnitObject adUnitObject = get(u);
            if (adUnitObject == null){
                log.error("adUnitObject not found");
                return;
            }
            result.add(adUnitObject);
        });
        return result;
    }

    public AdUnitObject get(Long key) {
        return map.get(key);
    }

    public void update(Long key, AdUnitObject value) {
        AdUnitObject adUnitObject = map.get(key);
        if (adUnitObject == null){
            map.put(key, value);
        }else {
            adUnitObject.update(value);
        }
    }

    public void add(Long key, AdUnitObject value) {
        map.put(key, value);
    }

    public void delete(Long key, AdUnitObject value) {
        map.remove(key);
    }
}
